package com.yindian.cos.easy.security.authentication.login.social.weixin;

import com.alibaba.fastjson.JSONObject;
import com.yindian.cos.easy.security.authentication.login.social.core.AbstractUserInfoFactory;
import com.yindian.cos.easy.security.authentication.login.social.core.AccessToken;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.exception.UserInfoException;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.WeiXinProperties;
import org.springframework.web.client.RestTemplate;

/**
 * 微信获取UserInfo默认实现
 *
 * @author zhangchuanhao
 * @create 2018/11/20 10:50
 */
public class WeiXinUserInfoFactory extends AbstractUserInfoFactory<WeiXinUserInfo> {

    private final EasySecurityProperties easySecurityProperties;

    private final RestTemplate restTemplate;

    public WeiXinUserInfoFactory(EasySecurityProperties easySecurityProperties, RestTemplate restTemplate) {
        this.easySecurityProperties = easySecurityProperties;
        this.restTemplate = restTemplate;
    }

    @Override
    public WeiXinUserInfo getUserInfo(AccessToken accessToken) {
        try {
            String token = accessToken.getAccessToken();
            String openId = accessToken.getOpenId();
            return getUserInfo(token, openId);
        } catch (Exception ex) {
            throw new UserInfoException(ProviderName.WEIXIN + "登录获取用户信息失败", ex.getCause());
        }
    }

    /**
     * 获取用户信息
     *
     * @param accessToken
     * @return
     */
    protected WeiXinUserInfo getUserInfo(String accessToken, String openId) {
        WeiXinProperties weiXinProperties = easySecurityProperties.getWeixin();
        String url = weiXinProperties.getUserInfoUrl();
        url += "?access_token=" + accessToken;
        url += "&openid=" + openId;
        String result = restTemplate.getForObject(url, String.class);
        WeiXinUserInfo weiXinUserInfo = JSONObject.parseObject(result, WeiXinUserInfo.class);
        return weiXinUserInfo;
    }
}
